<template>
  <div class="upload-file">
    <el-upload
      :drag="drag"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      :data="data"
      :accept="accept"
      class="upload-file-uploader"
      ref="upload"
    >
      <!-- 上传按钮 -->
      <template v-if="drag">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
      <el-button v-else size="mini" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
        的文件
      </div>
    </el-upload>

    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in list">
        <el-link :href="filePrePath+file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="getAttachmentInfo(file)" type="primary">详情</el-link>
          <el-link :underline="false" @click="delAttachmentByFilePath(index,file.url)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {delAttachmentByFilePath, getAttachmentByFilePath} from "@/api/system/attachment";

export default {
  name: 'AttachmentUpload',
  props: {
    /**
     * 值类型 path和object,默认为path
     * path时value存储路径(或路径数组)
     * 为object时value存储对象(或对象数组)
     */
    valueType: {
      type: String,
      default: 'path'
    },
    // 值
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 20,
    },
    //文件限制数
    limit: {
      type: Number,
      default: 1
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf"]
    },
    // 是否为拖拽框
    drag: {
      type: Boolean,
      default: false
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    //业务类型 默认普通附件
    businessType: {
      type: String,
      default: 'normal'
    },
    //删除时是否删除本地文件
    deleteFileOnRemove: {
      type: Boolean,
      default: false
    },
    //附件说明
    remark: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/attachment/uploadAttachment", // 上传的图片服务器地址
      filePrePath: process.env.VUE_APP_BASE_API + '/profile',
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      data: {
        //业务类型
        businessType: this.businessType,
        remark: this.remark
      },
      fileList: [],
    };
  },
  computed: {
    // 接收文件类型
    accept() {
      let fileType = this.fileType;
      if (fileType && fileType.length > 0) {
        return fileType.map(t => '.' + t).join(',');
      }
      return null;
    },
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    // 列表
    list() {
      //id,businessType,fileName,realName,filePath,fileExt,remark,saveTime,saveUser,downloadPath
      let temp = 1;
      if (this.value) {
        // 首先将值转为数组
        const list = Array.isArray(this.value) ? this.value : [this.value];
        // 然后将数组转为对象数组
        return list.map((item) => {
          let itemInfo = {};
          if (typeof item === "string") {
            itemInfo = {name: item, url: item, uid: new Date().getTime() + temp++};
          } else {
            //设置name和url
            itemInfo = {
              ...item,
              uid: item.id,
              name: item.fileName,
              url: item.filePath
            };
          }
          return itemInfo;
        });
      } else {
        this.fileList = [];
        return [];
      }
    },
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 文件个数超出
    handleExceed() {
      let limit = this.limit;
      this.$message.error(`最多允许上传${limit}个文件`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功");
      //根据类型判断
      let isArray = Array.isArray(this.value);
      if (isArray) {
        let arr = [];
        if (this.valueType === 'path') {
          arr = this.value.concat([res.data.filePath]);
        } else {
          arr = this.value.concat([res.data]);
        }
        this.$emit("input", arr);
      } else {
        if (this.valueType === 'path') {
          this.$emit("input", res.data.filePath);
        } else {
          this.$emit("input", res.data);
        }
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
      }
      return name;
    },
    //附件详情
    getAttachmentInfo(file) {
      if (this.valueType === 'path') {
        getAttachmentByFilePath(file.url).then(res => {
          if (res.data) {
            this.showFileInfo(res.data);
          } else {
            this.$alert(
              `服务器未存储该链接文件信息`,
              '文件详情',
              {
                dangerouslyUseHTMLString: true
              }
            )
          }
        })
      } else {
        this.showFileInfo(file);
      }
    },
    //显示文件信息
    showFileInfo(fileInfo) {
      this.$alert(
        `原文件名: <b>${fileInfo.fileName}</b> <br> 存储名称: <b>${fileInfo.realName}</b> <br> 上传时间: <b>${fileInfo.saveTime}</b><br> 上传人员: <b>${fileInfo.saveNickName}</b>`,
        '文件详情',
        {
          dangerouslyUseHTMLString: true
        }
      )
    },
    //删除文件
    delAttachmentByFilePath(index, filePath) {
      let _this = this;
      this.$modal.confirm('是否确认删除?').then(() => {
        _this.fileList.splice(index, 1);
        //设置value
        let isArray = Array.isArray(this.value);
        if (isArray) {
          this.value.splice(index, 1);
        } else {
          _this.$emit("input", '');
        }
        //删除本地文件
        if (this.deleteFileOnRemove) {
          delAttachmentByFilePath(filePath);
        }
      })
    }
  },
  created() {
    this.fileList = this.list;
  },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
